package brinaryTree;

import java.util.ArrayList;
import java.util.List;

public class N530_MinAbsoluteDifferenceInBST {
    private int min = Integer.MAX_VALUE;
    private TreeNode pre;

    public int getMinimumDifference(TreeNode root) {
        travel(root);
        return min;
    }

    private void travel(TreeNode cur) {
        if (cur == null) return;
        travel(cur.left);
        if (pre != null) {
            min = Math.min(min, cur.val - pre.val);
        }
        pre = cur;
        travel(cur.right);

    }


    private List<Integer> list = new ArrayList<>();

    public int getMinimumDifference_ToArray(TreeNode root) {
        traversal_ToArray(root);
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < list.size() - 1; i++) {
            min = Math.min(list.get(i + 1) - list.get(i), min);
        }
        return min;
    }

    private void traversal_ToArray(TreeNode node) {
        if (node.left != null) traversal_ToArray(node.left);
        list.add(node.val);
        if (node.right != null) traversal_ToArray(node.right);
    }


}
